﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;

namespace TopShooter.Editor.Actions
{
	public class PlaceEntityAction : EditorAction
	{
		public List<Vector2> Locations;
		public Entity ModelEntity;
		public List<Entity> NewEntities;

		public PlaceEntityAction(Entity entity)
		{
			ModelEntity = entity;
			Locations = new List<Vector2>();
		}
		public void AddLocation(Vector2 loc)
		{
			Locations.Add(loc);
		}
		public override string ToString()
		{
			return "place(" + ModelEntity + ")";
		}

		protected override bool OnApply(Scene scene)
		{
			if (NewEntities == null)
			{
				NewEntities = new List<Entity>(Locations.Count);
				foreach (var loc in Locations)
				{
					Coordinate c = Coordinate.FromLocation(loc);
					Entity existingEntity = scene.GetEntityAtCoordinate(c);

					if (existingEntity == null)
					{
						var e = ModelEntity.Clone();
						e.AddToScene(scene, loc);
						NewEntities.Add(e);
					}
					
				}
			}
			else { } // has already been applied
			return NewEntities.Count > 0;
		}

		protected override void OnUndo(Scene scene)
		{
			foreach (Entity e in NewEntities)
			{
				e.RemoveFromScene();
			}
			NewEntities.Clear();
		}

		protected override void AdjustLocation(int minColumn, int minRow)
		{
			for (int i = 0; i < Locations.Count; i++)
			{
				Vector2 loc = Locations[i];
				loc.X -= minColumn * Tile.Size.X;
				loc.Y -= minRow * Tile.Size.Y;
				Locations[i] = loc;
			}
		}
	}
}
